import { getPage, getImage } from '../../utils/config';
import api from '../../utils/api';
import wxApi from '../../utils/wxApi';
import { promisify, http, $toast, $query } from '../../utils/utils';
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        getPage: getPage,
        getImage: getImage,
        filterId: 1,
        filterType: 0,
        loading: 0,
        tabbarActive: 1,
        logged: 0,
        catsLoad: false,
        pageSize: 20,
        pageIndex: 1,
        nextPage: true,
        orders: 'desc',
        userId: '',
        shopNo: '',
        loadmore: false,
        loaddone: false,
        abnor: false,
    },

    /**
     * 返回上一页
     */
    goBackTap() {
        wxApi.navigateBack(1);
    },

    /**
     * 店铺搜索
     */
    visitSearch() {
        wxApi.navigateTo(getPage.shopSearch, {
            id: this.data.shopNo,
            cid: 0,
        });
    },

    /**
     * 店铺分类
     */
    catsClick(e) {
        const { id } = e.currentTarget.dataset || e.target.dataset;
        wxApi.navigateTo(getPage.shopSearch, {
            id: this.data.shopNo,
            cid: id,
        });
    },

    /**
     * 页面切换
     */
    pageChange(e) {
        const { detail } = e;
        let { tabbarActive, shopNo, catsLoad, loading } = this.data;

        if(detail !== tabbarActive){
            tabbarActive = detail;

            if (detail == 3 || detail == 0) {
                $toast(`功能开发中~`);
                return false;
            }

            //恢复页面
            if (detail != 1) {
                this.setData({
                    headingTop: '',
                    headingOpacity: 1,
                })
            }

            //获取分类
            if (detail == 2 && !catsLoad) {
                catsLoad = true;
                loading = 0;

                this.setData({ catsLoad, loading });

                http.get(api.default, {
                    data: {
                        action: 'getshopcategorylist',
                        shopno: shopNo
                    }
                }, false).then((res) => {
                    const { data } = res.data;

                    this.setData({ 
                        catsInfo: data.list,
                        loading: 1,
                    })
                })
            }

            this.setData({ tabbarActive });
        }
    },

    /**
     * 关注店铺
     */
    followClick() {
        const { logged, userId, shopInfo, shopNo } = this.data;
        if (logged){
            if (!shopInfo.is_fav_shop){
                http.post(api.default, {
                    data: {
                        action: 'fav_shop',
                        userid: userId,
                        shopid: shopInfo.shopid,
                    }
                }).then((res) => {
                    $toast(`收藏成功`,{
                        icon: 'success'
                    });
                    shopInfo.fans = shopInfo.fans + 1; 
                    shopInfo.is_fav_shop = true;
                    this.setData({ shopInfo });
                })
            }else{
                $toast(`已经收藏了哦`, {
                    time: 2500
                });
            }
        }else{
            this.jumpLogin();
        }
    },

    /**
     * 跳转登录页
     */
    jumpLogin() {
        wxApi.setStartPage({ id: this.data.shopNo });
        wxApi.navigateTo(getPage.login);
    },

    /**
     * 筛选产品
     */
    tabsFilterTap(e) {
        const { dataset } = e.currentTarget|| e.target;
        let { filterType, filterId } = this.data;
        let type, typeText;
        
        if (dataset.id != 3 && filterId == dataset.id) return false;

        if (dataset.id == 3) {
            switch (filterType) {
                case 0:
                    type = 1;
                    typeText = 'asc';
                break;
                case 1:
                    type = 2;
                    typeText = 'desc';
                break;
                case 2:
                    type = 1;
                    typeText = 'asc';
                break;
            }

            this.setData({
                filterType: type,
                orders: typeText,
            })
        } else {
            this.setData({
                filterType: 0,
                orders: 'desc',
            });
        }

        this.setData({
            filterId: dataset.id,
            productsInfo: [],
            pageIndex: 1,
            headingTop: this.headInfo.height,
            headingOpacity: 1,
            nextPage: true,
            loadmore: false,
            loaddone: false,
            abnor: false,
            loading: 0,
        });

        let { pageSize, loaddone, abnor } = this.data;

        //更新商品数据
        this.getShopProductsInfo((data) => {

            //判断是否有数据
            if (data.list.length == 0) {
                abnor = true;
            }

            //判断是否加载完
            if (data.list.length < pageSize) {
                loaddone = true;
            }

            this.setData({
                productsInfo: data.list,
                loading: 1,
                loaddone,
                abnor,
            });
        });
    },

    /**
     * 监听页面--滚动
     */
    scrollChange(e) {
        let { scrollTop, scrollHeight } = e.detail;
        let headingTop, headingOpacity, mainHeight;
        const { height } = this.headInfo;
        const { tabbarActive } = this.data;

        if (scrollTop <= 0 || scrollTop >= scrollHeight || tabbarActive != 1) return false;

        $query.select('#main', (data) => {
            mainHeight = data.height;

            if (scrollTop > this.scrollTop || scrollTop >= scrollHeight) {
                //向下滚动 
                if (scrollTop < height) {
                    headingTop = height - scrollTop;
                    headingOpacity = scrollTop / height > 1 ? 0 : 1 - (scrollTop / height);
                    this.setData({ headingTop, headingOpacity });
                } else if (scrollTop > height && headingTop !== height) {
                    headingTop = 0;
                    headingOpacity = 0;
                    this.setData({ headingTop, headingOpacity });
                }
            } else if ((scrollTop + mainHeight) < this.scrollHeight) {
                //向上滚动
                headingTop = height;
                headingOpacity = 1;
                this.setData({ headingTop, headingOpacity });
            }

            //给scrollTop重新赋值
            this.scrollTop = scrollTop;
            this.scrollHeight = scrollHeight;
        })
    },

    /**
     * 监听页面--滚动上拉
     */
    pullUp(e) {
        let { pageIndex, nextPage, loadmore } = this.data;

        if(nextPage && !loadmore){
            pageIndex++;
            loadmore = true;

            this.setData({ pageIndex, loadmore });

            this.getShopProductsInfo((data) => {
                let { productsInfo, pageSize, loaddone } = this.data;

                //判断是否加载完
                if (data.list.length < pageSize) {
                    loaddone = true;
                }
                loadmore = false;
                productsInfo = productsInfo.concat(data.list);

                this.setData({ productsInfo, loadmore, loaddone });
            })
        }
    },

    /**
     * 获取商品--网络请求
     */
    getShopProductsInfo(cb, a = false) {
        let { shopNo, pageSize, pageIndex, nextPage, abnor, filterId, orders } = this.data;

        http.get(api.default, {
            data: {
                action: 'getstoresproducts',
                cid: 0,
                keyword: '',
                pagesize: pageSize,
                pageindex: pageIndex,
                shopno: shopNo,
                ordersid: filterId,
                orders: orders,
            }
        }, a).then((res) => {
            const { data } = res.data;
            
            //判断是否还有下一页
            if(data.list.length < pageSize){
                nextPage = false;
            }

            this.setData({ nextPage });

            cb && cb(data);
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        
        /**
         * 店铺id
         */
        if(JSON.stringify(options) !== '{}'){
            this.setData({ shopNo: options.id });
        }

        /**
         * 获取system信息
         */
        promisify(wx.getSystemInfo)().then(res => {
            //获取右上角胶囊信息
            this.setData({
                navbar: wx.getMenuButtonBoundingClientRect(),
                window: res,
            })
        });

        /**
         * 获取用户信息 
         */
        let logged, userId = '';
        app.getLogin().then((res) => {
            logged = res.code;
            userId = res.data.user.user_id;
        }).catch((res) => {
            logged = res;
        }).finally(() => {
            this.setData({ logged, userId });
            /**
             * 获取店铺信息
             */
            let { shopNo, pageSize, loaddone, abnor } = this.data;
            http.post(api.default, {
                data: {
                    action: 'getstoresinfo',
                    shopno: shopNo,
                    userid: userId,
                }
            }, false).then((res) => {
                const { data } = res.data;

                this.setData({ shopInfo: data });
                this.getShopProductsInfo((data) => {

                    //判断是否有数据
                    if (data.list.length == 0) abnor = true;
                    //判断是否加载完
                    if (data.list.length < pageSize) loaddone = true;
                    
                    this.setData({ productsInfo: data.list, loading: 1, loaddone, abnor });
                });
            });
        });

        /**
         * scrollTop
         */
        this.scrollTop = 0;
        this.scrollHeight = 0;

        /**
         * 获取收缩对象高度
         */
        $query.select('#headInfo', (data) => {
            this.headInfo = data;
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})